package com.jiaquyun.jcyx.jetpack.mode

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.jiaquyun.jcyx.base.BaseViewModel
import com.jiaquyun.jcyx.entity.*
import com.jiaquyun.jcyx.jetpack.api.UserRepository
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.HttpResponseData
import com.module.lemlin.http.SubscribeViewModel
import com.module.lemlin.owner.OwnerApplication
import java.lang.StringBuilder

class AddressViewModel(application: Application) : BaseViewModel(application) {

    private val mUserRepository = UserRepository()

    val mPickerData: ProvinceUIData by lazy {
        getProvinceUIList(getProvinceList(OwnerApplication.application))
    }

    val addressListLiveData = MutableLiveData<HttpResponseBody<AddressListResponse>>()
    fun userAddressList() {
        setRxLifeScope(SubscribeViewModel(addressListLiveData)) {
            mUserRepository.userAddressList()
        }
    }

    val addressSaveLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userAddressSave(save: AddressSave) {

        val pca = save.addressIndexes ?: ""
        val province = mPickerData.provinceUIList
        val options1 = province.indexOfFirst { pca.contains(it.provinceName) }
        val city = province[options1].cityList
        val options2 = city.indexOfFirst { pca.contains(it.cityName) }
        val area = city[options2].areaList
        val options3 = area.indexOfFirst { pca.contains(it.areaName) }

        val addressIndexes = StringBuilder().append(province[options1].provinceName)
            .append("-").append(city[options2].cityName)
            .append("-").append(area[options3].areaName)
        setRxLifeScope(SubscribeViewModel(addressSaveLiveData)) {
            mUserRepository.userAddressSave(save.apply {
                this.addressIndexes = addressIndexes.toString()
            })
        }
    }

    val addressDetailLiveData = MutableLiveData<HttpResponseBody<AddressDetailsResponse>>()
    fun userAddressDetail(id: Int) {
        setRxLifeScope(SubscribeViewModel(addressDetailLiveData)) {
            mUserRepository.userAddressDetail(id.toString())
        }
    }

    val addressDeleteLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userAddressDelete(id: Int) {
        setRxLifeScope(SubscribeViewModel(addressDeleteLiveData)) {
            mUserRepository.userAddressDelete(id.toString())
        }
    }
}